<template>
  <view>

    <view @tap="close_modal" class="drawer_screen" v-if="show_modal"></view>
    <view class="drawer_box" v-if="show_modal">
      <view class="drawer_title">应收</view>
      <view class="totalPrice">￥{{ totalPrice }}</view>
			<view class="change_title">
				选择支付方式
			</view>
      <view class="weui-cells weui-cells_after-title">
        <!--//1=微信支付 2=余额支付 3=积分支付 4=货到付款 5=支付宝APP支付 10=抖音支付-->
        <radio-group
            @change="radioChange1"
            class="radio-group"
            name="radiogroup"
						iconSize="10"
        >


          <!-- #ifdef MP-WEIXIN -->
          <label>
            <view class="weui-cell">
              <view class="zfimg">
                <image src="https://yunkeososyunchuc.bc8t.cn/ymq_canyino2o/static/weixin.png"></image>
              </view>
              <view class="weui-cell__bd">微信支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 1" value="wxzf_miniapp"></radio>
              </view>
            </view>
          </label>
          <!-- #endif -->


          <!-- #ifdef MP-TOUTIAO -->
          <label>
            <view class="weui-cell">
              <view class="zfimg">
                <image src="/static/douyin.png"></image>
              </view>
              <view class="weui-cell__bd">抖音支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 10" value="douyin_zf"></radio>
              </view>
            </view>
          </label>
          <!-- #endif -->


          <!-- #ifdef APP-PLUS -->
          <label>
            <view class="weui-cell">
              <view class="zfimg">
                <image
                    src="https://ymqycc.oss-cn-chengdu.aliyuncs.com/ymqzho2o/static/ymq_canyino2o/zhifubao.png"></image>
              </view>
              <view class="weui-cell__bd">支付宝支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 5" value="zfb_app_zf"></radio>
              </view>
            </view>
          </label>
          <!-- #endif -->


          <!-- #ifdef H5 -->
          <label v-if="!is_h5_wxgzh">
            <view class="weui-cell">
              <view class="zfimg">
                <image
                    src="https://ymqycc.oss-cn-chengdu.aliyuncs.com/ymqzho2o/static/ymq_canyino2o/zhifubao.png"></image>
              </view>
              <view class="weui-cell__bd">支付宝H5支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 12" value="zfb_h5_zf"></radio>
              </view>
            </view>
          </label>
          <label v-if="!is_h5_wxgzh">
            <view class="weui-cell">
              <view class="zfimg">
                <image src="https://yunkeososyunchuc.bc8t.cn/ymq_canyino2o/static/weixin.png"></image>
              </view>
              <view class="weui-cell__bd">微信H5支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 13" value="wx_h5_zf"></radio>
              </view>
            </view>
          </label>
          <label v-if="is_h5_wxgzh">
            <view class="weui-cell">
              <view class="zfimg">
                <image src="https://yunkeososyunchuc.bc8t.cn/ymq_canyino2o/static/weixin.png"></image>
              </view>
              <view class="weui-cell__bd">微信公众号支付</view>
              <view class="weui-cell__ft">
                <radio :checked="zffs == 14" value="wxgzh_h5_zf"></radio>
              </view>
            </view>
          </label>
          <!-- #endif -->


          <!--开启余额支付-->
          <label v-if="kqyue">
            <view class="weui-cell">
              <view class="zfimg">
                <image src="/static/ymq_canyino2o/ye1.png"></image>
              </view>
              <view class="weui-cell__bd">
                余额支付
                <text class="yetext">您的余额 {{ user_wallet }}</text>
              </view>
              <view class="weui-cell__ft">
                <radio
                    :checked="zffs == 2"
                    color="#FF9700"
                    :disabled="!kqyue"
                    value="yezf"
                ></radio>
              </view>
            </view>
          </label>
          <label v-if="hdfk">
            <view class="weui-cell" >
              <view class="zfimg">
                <image
                    src="https://yunkeososyunchuc.bc8t.cn/ymq_canyino2o/static/wmtime.png"
                    style="height: 50rpx"
                ></image>
              </view>
              <view class="weui-cell__bd">
                货到付款
                <text class="yetext" style="color: #999"></text>
              </view>
              <view class="weui-cell__ft">
                <radio
                    :checked="zffs == 4"
                    color="#34aaff"
                    :disabled="!hdfk"
                    value="hdfk"
                ></radio>
              </view>
            </view>
          </label>
        </radio-group>
      </view>
      <view class="drawer_title1">
        您选择的{{ zfwz }}
        <text v-if="zffs == 3">({{ jf_proportion }}积分可抵1元)</text>
      </view>
      <button :class="btntype" :disabled="zfz" @click.stop="start_pay_order">
        <view v-if="!zfz && zffs != 4">
          确定支付
          <!-- <text class="zftext">￥{{ totalPrice }}</text> -->
        </view>
        <view v-if="!zfz && zffs == 4">
          确定到付
          <!-- <text class="zftext">￥{{ totalPrice }}</text> -->
        </view>
        <view v-if="zfz">
          <text class="zfztext">支付中...</text>
        </view>
      </button>
      <!--<view>-->
      <!--  pay_mp_openid: {{pay_mp_openid}}-->
      <!--</view>-->
    </view>
		<image src="/static/ymq_canyino2o/pay-close.png" mode="" @click="close_modal" style="width: 60rpx;
    height: 60rpx;
    position: fixed;
    z-index: 999999;
    bottom: 15%;
    left: 50%;
    transform: translateX(-50%);"></image>
  </view>

</template>
<script>
// import jWeixin from 'dy_utils/jweixin-module1_6.js'
export default {
  name: 'daya-pay',
  props: {
    type: {
      default: 0,  // 不传递=外卖订单  2=充值订单 3=会员订单 95=跑腿订单
    },
    order_id: {
      default: 0,  // 订单id
    },
    mp_openid: {
      default: '',  // 小程序环境需要用的mp_openid
    },
    show_pay_box: {
      default: true
    }, //显示支付窗口
    kqyue: {
      default: true
    }, //开启余额支付
    jf_proportion: {
      default: 100
    }, //多少积分=1元
    totalPrice: {
      default: 10
    }, //需支付的总金额
    user_wallet: {
      default: 0
    }, //用户余额
    hdfk: {
      default: true
    }, //开启货到付款
  },
  data() {
    return {
      is_h5_wxgzh: false,

      zfz: false,
      show_modal: this.show_pay_box,

      // #ifdef MP-WEIXIN
      pay_type_str: 'wxzf_miniapp',
      zffs: 1,
      zfwz: '微信支付(mini)',
      btntype: 'btn_ok1',
      // #endif

      // #ifdef MP-TOUTIAO
      pay_type_str: 'douyin_zf',
      zffs: 10,
      zfwz: '抖音支付(mini)',
      btntype: 'btn_ok1',
      // #endif

      // #ifdef H5
      pay_type_str: 'yezf',
      zffs: 2,
      zfwz: '余额支付',
      btntype: 'btn_ok2',
      // #endif

      // #ifdef APP-PLUS
      pay_type_str: 'zffs',
      zffs: 5,
      zfwz: '支付宝App支付',
      btntype: 'btn_ok5',
      // #endif

      pay_mp_openid: '',
    }
  },
  mounted() {
    // #ifdef H5
    //判断当前浏览器环境是否是微信公众号
    if (navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
      this.is_h5_wxgzh = true
    }
    // #endif


    if (this.mp_openid == '' || this.mp_openid == undefined || this.mp_openid == null) {
      // #ifdef MP-WEIXIN
      this.pay_mp_openid = uni.getStorageSync('openid_wx_mini');
      // #endif

      // #ifdef H5
      this.pay_mp_openid = uni.getStorageSync('openid_wx_gzh');
      // #endif

      // #ifdef MP-TOUTIAO
      this.pay_mp_openid = uni.getStorageSync('openid_toutiao_mini');
      // #endif
    } else {
      this.pay_mp_openid = this.mp_openid;
    }
  },
  watch: {
    show_modal: (newVal, oldVal) => {
      if (newVal) {
        this.show_modal = newVal
      }
    }
  },
  methods: {
		close() {
			this.show_modal = false
		},
    start_pay_order() {
      let _this = this

      //如果是余额支付
      if ('yezf' == this.pay_type_str) {
        if ('下单失败' != this.order_id) {
          getApp().globalData.util.request({
            url: 'entry/wxapp/pay_user_wallet',
            cachetime: '0',
            data: {
              type: this.type,
              // openid: this.pay_mp_openid, //余额支付又不需要
              // money: this.totalPrice,
              order_id: this.order_id
            },
            success: (res) => {
              if (res.data.code == 1) {
                _this.show_modal = false;
                _this.$emit('pay_success', this.order_id)
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'loading'
                })
                _this.$emit('pay_error', "下单失败");
              }
            }
          })

        } else {
          uni.showToast({
            title: '支付失败',
            icon: 'loading'
          })
          _this.$emit('pay_error', "下单失败");
        }
      }

      //如果是货到付款支付
      if ('hdfk' == this.pay_type_str) {
        if ('下单失败' != this.order_id) {

          getApp().globalData.util.request({
            url: 'entry/wxapp/pay_user_hdfk',
            cachetime: '0',
            data: {
              type: this.type,
              order_id: this.order_id
            },
            success: (res) => {
              if (res.data.code == 1) {
                _this.show_modal = false;
                _this.$emit('pay_success', this.order_id)
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'loading'
                })
                _this.$emit('pay_error', "下单失败");
              }
            }
          })

        } else {
          uni.showToast({
            title: '支付失败',
            icon: 'loading'
          })
          _this.$emit('pay_error', "下单失败");
        }
      }


      //如果是微信支付
      if ('wxzf_miniapp' == this.pay_type_str) {
        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
        } else {
          if ('下单失败' != this.order_id) {
            getApp().globalData.util.request({
              url: 'entry/wxapp/pay_wx_mini',
              cachetime: '0',
              data: {
                type: this.type,
                openid: this.pay_mp_openid, //微信支付需要
                order_id: this.order_id
              },
              success: (t) => {
                if (t.data.code == 0) {
                  uni.showToast({
                    title: t.data.msg,
                    icon: 'loading',
                    duration: 1000
                  })
                  return
                }
                uni.requestPayment({
                  "provider": "wxpay",
                  "orderInfo": {},
                  appid: t.data.appid,
                  timeStamp: t.data.timeStamp,
                  nonceStr: t.data.nonceStr,
                  package: t.data.package,
                  signType: t.data.signType,
                  paySign: t.data.paySign,
                  fail: (t) => {
                    console.error("uni支付失败", t)
                  },
                  success: (t) => {
                  },
                  complete: (t) => {
                    if ('requestPayment:fail cancel' == t.errMsg) {
                      uni.showToast({
                        title: '取消支付',
                        icon: 'loading',
                        duration: 1000
                      })
                      _this.$emit('pay_error', "下单失败");
                    }
                    if ('requestPayment:ok' == t.errMsg) {
                      _this.show_modal = false
                      _this.$emit('pay_success', this.order_id)
                    }
                  }
                });
              }
            })
          }
        }
      }

      //如果是支付宝app支付
      if ('zfb_app_zf' == this.pay_type_str) {

        //沙箱模式app支付
        let EnvUtils = plus.android.importClass('com.alipay.sdk.app.EnvUtils');
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);


        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
        } else {
          if ('下单失败' != this.order_id) {
            getApp().globalData.util.request({
              url: 'entry/wxapp/pay_zfb_app_zf',
              cachetime: '0',
              data: {
                type: this.type,
                // openid: this.pay_mp_openid, //支付宝APP支付不需要
                // money: this.totalPrice,
                order_id: this.order_id
              },
              success: (pay_res) => {
                console.log("pay_res", pay_res.data)
                uni.requestPayment({
                  provider: 'alipay',
                  orderInfo: pay_res.data,
                  success: (t) => {
                  },
                  fail: (t) => {
                    console.log("pay_zfb_app_zf fail", t)
                    _this.$emit('pay_error', "支付失败");
                  },
                  complete: (t) => {
                    if ('requestPayment:fail cancel' == t.errMsg) {
                      uni.showToast({
                        title: '取消支付',
                        icon: 'loading',
                        duration: 1000
                      })
                      _this.$emit('pay_error', "支付失败");
                    }
                    if ('requestPayment:ok' == t.errMsg) {
                      _this.show_modal = false
                      _this.$emit('pay_success', this.order_id)
                    }
                  }
                })
              }
            })
          }
        }
      }

      //如果是抖音app支付
      if ('douyin_zf' == this.pay_type_str) {


        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
          return
        }
        if ('下单失败' != this.order_id) {
          getApp().globalData.util.request({
            url: 'entry/wxapp/pay_toutiao_mini',
            cachetime: '0',
            data: {
              type: this.type,
              openid: this.pay_mp_openid, //抖音支付需要
              // money: this.totalPrice,
              order_id: this.order_id
            },
            success: (pay_res) => {
              console.log("pay_res", pay_res.data)
              tt.pay({
                orderInfo: {
                  order_id: pay_res.data.data.order_id,
                  order_token: pay_res.data.data.order_token
                },
                service: 5,
                _debug: 1,
                success: (res) => {
                  console.log("支付完成", res)
                  if (res.code == 0) {
                    // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
                    // 但是最终状态要以商户后端结果为准

                    // _this.show_modal=false
                    console.log("支付完成")
                    _this.$emit('pay_success', this.order_id)
                  } else {
                    _this.$emit('pay_error', "支付失败");
                  }
                },
                fail: (t) => {
                  console.log("douyin_zf fail", t)
                  _this.$emit('pay_error', "支付失败");
                },
              })
            }
          })
        }
      }


      //如果是微信h5支付
      if ('wx_h5_zf' == this.pay_type_str) {
        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
          return
        }
        if ('下单失败' != this.order_id) {
          console.log("发起微信支付001")
          // console.log("jWeixin",jWeixin)
          // jWeixin.ready(()=>{
          //   //发起微信支付
          //   console.log("发起微信支付002")
          // });
          getApp().globalData.util.request({
            url: 'entry/wxapp/pay_h5_wx',
            cachetime: '0',
            data: {
              type: this.type,
              openid: this.pay_mp_openid, //抖音支付需要
              // money: this.totalPrice,
              order_id: this.order_id
            },
            success: (pay_res) => {
              console.log("pay_res", pay_res.data)
              //如果pay_res.data中有mweb_url这个属性,且不为空,则是跳转的url
              if (pay_res.data && pay_res.data.mweb_url != undefined && pay_res.data.mweb_url != '') {
                //获取当前协议和域名
                let domain = window.location.protocol + "//" + window.location.host;
                window.location.href = pay_res.data.mweb_url + "&redirect_url=" + encodeURIComponent(domain);
              } else {
                uni.showToast({
                  title: '微信H5支付发起错误',
                  icon: 'loading',
                  duration: 1000
                })
              }
            }
          })

        }
      }


      //如果是微信公众号支付
      if ('wxgzh_h5_zf' == this.pay_type_str) {
        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
          return
        }
        if ('下单失败' != this.order_id) {
          console.log("发起微信支付001")
          // console.log("jWeixin",jWeixin)
          // jWeixin.ready(()=>{
          //   //发起微信支付
          //   console.log("发起微信支付002")
          // });
          getApp().globalData.util.request({
            url: 'entry/wxapp/pay_h5_wxgzh',
            cachetime: '0',
            data: {
              type: this.type,
              openid: this.pay_mp_openid, //公众号支付需要
              // money: this.totalPrice,
              order_id: this.order_id
            },
            success: (pay_res) => {
              console.log("pay_res", pay_res.data)

              //如果pay_res.data中有prepay_id
              if (pay_res.data && pay_res.data.prepay_id != undefined && pay_res.data.prepay_id != '') {

                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                      "appId": pay_res.data.appid,     //公众号ID，由商户传入
                      "timeStamp": pay_res.data.time,         //时间戳，自1970年以来的秒数
                      "nonceStr": pay_res.data.nonce_str, //随机串
                      "package": "prepay_id=" + pay_res.data.prepay_id,
                      "signType": pay_res.data.sign_type,         //微信签名方式：S
                      "paySign": pay_res.data.sign //微信签名
                    },
                    function (res) {
                      if (res.err_msg == "get_brand_wcpay_request:ok") {
                        // 使用以上方式判断前端返回,微信团队郑重提示：
                        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                        _this.show_modal = false
                        _this.$emit('pay_success', this.order_id)
                      } else {
                        _this.$emit('pay_error', "支付失败");
                      }
                    });

              } else {
                uni.showToast({
                  title: '微信公众号支付发起错误',
                  icon: 'loading',
                  duration: 1000
                })
              }
            }
          })

        }
      }


      //如果是支付宝h5支付
      if ('zfb_h5_zf' == this.pay_type_str) {

        if (0 == this.totalPrice) {
          uni.showModal({
            title: '提示',
            content: '0元买单请选择其他方式支付'
          })
          _this.zfz = false
        } else {
          if ('下单失败' != this.order_id) {
            getApp().globalData.util.request({
              url: 'entry/wxapp/pay_h5_zfb',
              cachetime: '0',
              data: {
                type: this.type,
                // openid: this.pay_mp_openid, //支付宝APP支付不需要
                // money: this.totalPrice,
                order_id: this.order_id
              },
              success: (pay_res) => {
                console.log("pay_res", pay_res.data)
                //如果pay_res.data中含有 alipaysubmit 则直接将dom添加到body中, 发起跳转,否则提示支付发起错误.
                if (pay_res.data.indexOf('alipaysubmit') != -1) {
                  document.querySelector('body').insertAdjacentHTML("beforeend", pay_res.data);
                  document.forms['alipaysubmit'].submit();
                } else {
                  uni.showToast({
                    title: '支付宝H5发起支付错误',
                    icon: 'loading',
                    duration: 1000
                  })
                  _this.$emit('pay_error', "支付发起错误");
                }
              }
            })
          }
        }

      }

    },
    close_modal() {
      this.show_modal = false
      this.$emit('close_pay_box', false)
    },
    radioChange1(t) {
      this.pay_type_str = t.detail.value
      //1=微信支付 2=余额支付 3=积分支付 4=货到付款 5=支付宝APP支付 10=抖音支付 12=支付宝H5支付 13=微信H5支付 14=微信公众号支付
      if ('wxzf_miniapp' == t.detail.value) {
        this.zffs = 1
        this.zfwz = '微信支付(mini)'
        this.btntype = 'btn_ok1'
      }
      if ('yezf' == t.detail.value) {
        this.zffs = 2
        this.zfwz = '余额支付'
        this.btntype = 'btn_ok2'
      }
      if ('jfzf' == t.detail.value) {
        this.zffs = 3
        this.zfwz = '积分支付'
        this.btntype = 'btn_ok3'
      }
      if ('hdfk' == t.detail.value) {
        this.zffs = 4
        this.zfwz = '货到付款'
        this.btntype = 'btn_ok4'
      }
      if ('zfb_app_zf' == t.detail.value) {
        this.zffs = 5
        this.zfwz = '支付宝APP支付'
        this.btntype = 'btn_ok5'
      }

      if ('douyin_zf' == t.detail.value) {
        this.zffs = 10
        this.zfwz = '抖音支付(mini)'
        this.btntype = 'btn_ok1'
      }

    }
  }
}
</script>

